package org.login.akka;

import akka.actor.typed.ActorRef;
import io.netty.channel.ChannelHandlerContext;
import org.common.utils.SpringUtils;
import org.common.akka.AkkaContext;
import org.common.akka.message.BaseMsg;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ConnectActorManager {

    private final Map<Long, ActorRef<BaseMsg>> connectActorMap = new ConcurrentHashMap<>();
    private final Map<Long, ActorRef<BaseMsg>> accountId2ConnectActorMap = new ConcurrentHashMap<>();

    public ActorRef<BaseMsg> getConnectActor(long connectId) {
        return connectActorMap.get(connectId);
    }
    public ActorRef<BaseMsg> getConnectActorByAccountId(long accountId) {
        return accountId2ConnectActorMap.get(accountId);
    }

    public static ConnectActorManager getInstance() {
        return SpringUtils.getBean(ConnectActorManager.class);
    }
    /**
     * 创建一个ConnectActor
     */
    public ActorRef<BaseMsg> createConnectActor(long connectId, ChannelHandlerContext ctx) {
        ActorRef<BaseMsg> actor = AkkaContext.createActor(ConnectActor.create(connectId, ctx), String.valueOf(connectId));
        connectActorMap.put(connectId, actor);
        return actor;
    }

    public boolean addConnectActorByAccountId(long accountId, long connectId) {
        ActorRef<BaseMsg> actor = connectActorMap.get(connectId);
        if (actor == null) {
            return false;
        }
        accountId2ConnectActorMap.put(accountId, actor);
        return true;
    }

    /**
     * 移除actor
     */
    public void removeConnectActor(long connectId) {
        connectActorMap.remove(connectId);
    }
    public void removeConnectActorByAccountId(long accountId) {
        connectActorMap.remove(accountId);
    }
}
